import _ from 'lodash';
import { Message } from '@arco-design/web-vue';
import * as Api from '@/api/filmRead/filmRead'
import { getLesionData } from '@/api/setting/setting';
import { commonList } from '@/api/common/common';
import { formComponentRead } from '@/api/projectDetail/projectDetail';
import { taskSeriesSearch } from '@/api/doctor/doctor';
import type { ImageCompItem } from '@/store/modules/filmReadHeader/type';
import type * as FilmReadType from '@/store/modules/filmRead/type';
import type * as FileReadApiType from '@/api/filmRead/filmRead.d';

/**
 * 通过接口请求得到的数据函数
 * @param route 当前请求接口的参数
 * @returns 返回处理后的接口数据
 */
export const getInterface = async (route: FilmRead.RouteParams) => {
  try {
    // 获取病灶数据
    const lesionParams = {
      page: 1,
      pageSize: 1000000,
    };
    const lesionList = await getLesionData(lesionParams);
    // 获取废片原因数据
    const commonData = await commonList();
    // 获取序列号
    let seriesList;
    const seriesParams = {
      taskId: +route.id
    }
    if (route.type === "create") {
      seriesList = await Api.getAnnoArList(seriesParams)
    } else {
      const taskInfo = JSON.parse(sessionStorage.getItem('task_info') || '{}');
      const arList = taskInfo.seriesAnnoList && taskInfo.seriesAnnoList.map(
        (item: { arId: number; seriesUid: string }) => ({
          id: item.arId,
          seriesUid: item.seriesUid,
        })
      );
      seriesList = {
        data: {
          arList
        }
      };
    }
    if(!seriesList.data.arList){
      return { seriesList: null }
    }
    // 获取配置结果，数据详情的详细信息
    const pageData = await Api.getInitSettingData(seriesParams);
    // 处理废片原因集合
    let discardCodeList;
    pageData.data.discardCodeList && (discardCodeList = commonData.data.discardReasons?.filter(item => pageData.data.discardCodeList.split(",").includes(item.value) && _.cloneDeep(item)))
    // 处理小征象字典
    let imageSeries: ImageCompItem[] = [];
    pageData.data.lesionList.length !== 0 && pageData.data.lesionList.map(item => {
      item.imageCompList && item.imageCompList.map(it => {
        imageSeries.push(it)
      })
    })
    // console.log(pageData.data.lesionList, "pageData.data.lesionList");
    // 对小征象去重
    let hash: {[x: number]: any} = {}
    imageSeries = imageSeries.reduce((item: ImageCompItem[], next: ImageCompItem) => {
      hash[next.componentId] ? "" : hash[next.componentId] = true && item.push(next);
      return item;
    }, []);
    // 请求获取大征象配置
    const seriesCompList: FilmReadType.Component[] = [];
    if (pageData.data.seriesCompList) {
      for await (const item of pageData.data.seriesCompList) {
        if ('componentId' in item) {
          const res = formComponentRead(item.componentId);
          if ((await res).data !== null) {
            seriesCompList.push({...(await res).data, required: item.required, componentId: item.componentId})
          } else {
            Message.error({
              content: '当前征象数据查询异常请联系管理员',
              duration: 3000
            })
            break;
          }
        }
      }
    }
    // 请求获取小征象配置
    const imageSeriesResList: FilmReadType.Component[] = [];
    for await (const item of imageSeries) {
      const res = formComponentRead(item.componentId);
      if ((await res).data !== null) {
        imageSeriesResList.push({...(await res).data, required: item.required, componentId: item.componentId})
      } else {
        Message.error({
          content: '当前征象数据查询异常请联系管理员',
          duration: 3000
        })
        break;
      }
    }
    // console.log(imageSeriesResList, "imageSeriesResList");
    const lesionToImageSeriesList: {[x: string]: any} = {};
    pageData.data.lesionList && pageData.data.lesionList.map(item => {
      const tempArr = item.imageCompList && item.imageCompList.map(it => imageSeriesResList.find(t => t.id === it.componentId));
      lesionToImageSeriesList[item.lesion] = tempArr;
    })
    // console.log(lesionToImageSeriesList, "lesionToImageSeriesList");
    pageData.data.seriesCompList = seriesCompList
    // 整理数据结果
    const resultData = {
      lesionList: lesionList.data.list,
      discardList: discardCodeList,
      windowList: commonData.data.windows,
      seriesList: seriesList.data.arList,
      pageSettingList: pageData.data,
      imageSeriesResList,
      lesionToImageSeriesList
    }
    return _.cloneDeep({...resultData});
  } catch (error) {
    Message.error({
      content: "数据处理失败，请联系管理员",
      closable: true,
      duration: 3000
    })
    console.log(error);
  }
}

/**
 * 通过接口请求得到的结果数据函数
 * @param id 当前序列结合的唯一主键id
 * @returns 返回处理后的结果数据
 */
export const getResultInterface = async (id: number) => {
  try {
    // 获取结果
    const resultParams = {
      arId: id
    };
    const resultDataList = await Api.getInitResultData(resultParams);
    return _.cloneDeep({
      resultDataList: resultDataList.data
    });
  } catch (error) {
    Message.error({
      content: "数据处理失败，请联系管理员",
      closable: true,
      duration: 3000
    })
    console.log(error);
  }
}

/**
 * 通过接口请求得到查阅已提交序列的结果的数据函数
 * @param route 当前请求接口的参数
 * @returns 返回当前处理后的数据集合
 */
export const getTaskInfoInterface = async (route: FilmRead.RouteParams) => {
  try {
    const params = {
      page: 1,
      pageSize: 10000,
      taskId: +route.id
    }
    const result = await taskSeriesSearch(params);
    return _.cloneDeep({
      seriesAllList: result.data.list
    })
  } catch (error) {
    Message.error({
      content: "数据处理失败，请联系管理员",
      closable: true,
      duration: 3000
    })
    console.log(error);
  }
}

/**
 * 通过store处理后的接口数据结合转换成配置型的字典数据结合
 * @param dataList 将store中的接口数据传入
 * @returns 返回字典数据集合
 */
export const getDictionaryData = (dataList: FilmReadType.InterfaceData) => {
  // 病灶数据字典
  const lesionList = {} as {[x: string | number]: any};
  dataList.lesionList && dataList.lesionList.length !== 0 && dataList.lesionList.map((item, index) => {
    lesionList[item.value] = _.cloneDeep({
      id: item.id,
      name: item.name,
      value: item.value,
      index
    });
  });
  // 大征象字典
  const seriesCompList = {} as {[x: string | number]: any};
  dataList.pageSettingList.seriesCompList && dataList.pageSettingList.seriesCompList.length !== 0 && dataList.pageSettingList.seriesCompList.map(item => {
    if ('id' in item) {
      seriesCompList[item.id] = item;
      delete seriesCompList[item.id].createTime;
      delete seriesCompList[item.id].updateTime;
    }
  })
  // 小征象字典
  const imageSeriesCompList = {} as {[x: string | number]: any};
  dataList.imageSeriesResList && dataList.imageSeriesResList.length !== 0 && dataList.imageSeriesResList.map(item => {
    imageSeriesCompList[item.id] = item;
    delete imageSeriesCompList[item.id].createTime;
    delete imageSeriesCompList[item.id].updateTime;
  });
  // 工具字典
  const toolList = {} as {[x: string | number]: any};
  dataList.pageSettingList.lesionList && dataList.pageSettingList.lesionList.length !== 0 && dataList.pageSettingList.lesionList.map(item => {
    // item.imageCompList && (item.imageCompList = item.imageCompList.map(t => JSON.stringify(imageSeriesCompList) !== '{}' && imageSeriesCompList[t.componentId]))
    if (item.imageCompList) {
      item.imageCompList = item.imageCompList.map(it => {
        if (JSON.stringify(imageSeriesCompList) !== '{}') {
          return _.cloneDeep({
            ...imageSeriesCompList[it.componentId],
            data: changeSeriesOptionsData(imageSeriesCompList[it.componentId].data, imageSeriesCompList[it.componentId].parameter ? JSON.parse(imageSeriesCompList[it.componentId].parameter) : null, imageSeriesCompList[it.componentId].type),
            parameter: imageSeriesCompList[it.componentId].parameter ? JSON.parse(imageSeriesCompList[it.componentId].parameter) : null,
            result: null
          })
        }
        return it;
      })
    }
    item.toolList && item.toolList.map((it, index) => {
      let list1 = toolList[it];
      if (!list1) {
        list1 = [];
        toolList[it] = list1;
      };
      list1.push({
        ...item,
        index
      });
    });
  });
  return {
    lesionList,
    seriesCompList,
    imageSeriesCompList,
    toolList
  };
}

/**
 * 字典数据处理函数
 * @param dataList 接口处理的数据集合
 * @param dictData 字典数据集合
 * @returns 处理后的字典数据集合
 */
export const getResultDictData = (dataList: FilmReadType.InterfaceData, dictData: FilmReadType.DictionaryData) => {
  // 病灶结果数据对应病灶结果字典
  const lesionDataList = {} as {[x: string | number]: FilmRead.LesionDataItem | FilmRead.LesionDataItem[]};
  // 病灶结果数据对应中间图片结果字典
  const imageDataList = {} as {[x: string | number]: any};
  // 病灶结果数据对应右侧小征象结果字典
  const imageSeriesDataList = {} as { [x: string | number]: any };
  // 针对超声视频标注帧段初始化结果帧段数据
  const videoDataList = {} as { [x: string | number]: FileReadApiType.LesionResultItem[] };
  // 超声视频页面帧段渲染集合
  let frameList = <FileReadApiType.GroupViewItem[]>[]
  // 针对超声视频标注帧段初始化结果的病灶数据 单帧及多帧
  const videoMultipleLesions = <FileReadApiType.LesionResultItem[]>[];
  const videoSingleLesions = <FileReadApiType.LesionResultItem[]>[];
  console.log(dataList, '接口');
  console.log(dictData, '字典数据');
  // 处理超声视频的groupList
  // if (dataList.pageSettingList.imageLayout === 'VIDEO_ANNO') {
  //   dataList.resultDataList.groupList
  // }
  dataList.resultDataList.groupList && (frameList = dataList.resultDataList.groupList.map(item => {
    const { info, ...newItem } = item;
    lesionDataList[item.id] = []
    return {
      ...newItem,
      info: JSON.parse(info || "{}"),
      eyeStatus: true,
      visibile: false
    };
  }))
  //单帧列表为空时，即没有groupid=0的项
  dataList.resultDataList.lesionResultList && (lesionDataList[0] = [])//单帧的列表初始为[],用于渲染绑定,不然新增第一个无法渲染
  dataList.resultDataList.lesionResultList &&
    dataList.resultDataList.lesionResultList.map((item, index) => {
      const {
        id,
        color,
        lesion,
        result,
        resultDetailMap,
        resultType,
        tool,
        groupId,
        alg,
        imageCompResultList,
      } = item;
      if (dataList.pageSettingList.imageLayout === 'VIDEO_ANNO') {
        // 超声视频
        // groupid为null 可能逻辑会有问题
        let list = lesionDataList[groupId];
        if (!list) {
          list = [];
          lesionDataList[groupId] = list;
        };
        if (Array.isArray(list)) {
          list.push({
            id,
            color,
            lesion: dictData.lesionList[lesion].name,
            code: lesion,
            tool,
            index,
            groupId,
            eyeStatus: true,
            alg
          });
        }
        
        // if (String(groupId) === "null") {
          
        // }
        // if (String(groupId) !== "null") {
          
        // }
        // lesionDataList[item.id] = {
        //   id,
        //   color,
        //   lesion: dictData.lesionList[lesion].name,
        //   code: lesion,
        //   tool,
        //   index,
        //   groupId,
        //   eyeStatus: true,
        //   alg,
        // };
      }
      if (dataList.pageSettingList.imageLayout !== 'VIDEO_ANNO') {
        // 大图或者mpr
        lesionDataList[item.id] = {
          id,
          color,
          lesion: dictData.lesionList[lesion].name,
          code: lesion,
          tool,
          index,
          eyeStatus: true,
        };
      }
      // if (index === -1) {
      //   lesionDataList[item.id] = {
      //     id: 'eb7884360cfa4c6e9f655460a56b223b',
      //     eyeStatus: true,
      //     visibile: false,
      //     code: '帧段-' + 'eb7884360cfa4c6e9f655460a56b223b',
      //     index,
      //     lesionList: [
      //       {
      //         id,
      //         color,
      //         lesion: dictData.lesionList[lesion].name,
      //         code: lesion,
      //         tool,
      //         index,
      //         itemEyeStatus: true,
      //       },
      //       {
      //         id,
      //         color,
      //         lesion: dictData.lesionList[lesion].name,
      //         code: lesion,
      //         tool,
      //         index,
      //         itemEyeStatus: true,
      //       },
      //     ],
      //   };
      //   lesionDataList[item.id + 2] = {
      //     id: 'eb7884360cfa4c6e9f655460a56b2232',
      //     eyeStatus: true,
      //     visibile: false,
      //     code: '帧段-' + 'eb7884360cfa4c6e9f655460a56b223b',
      //     index,
      //     lesionList: [
      //       {
      //         id,
      //         color,
      //         lesion: dictData.lesionList[lesion].name,
      //         code: lesion,
      //         tool,
      //         index,
      //         itemEyeStatus: true,
      //       },
      //       {
      //         id,
      //         color,
      //         lesion: dictData.lesionList[lesion].name,
      //         code: lesion,
      //         tool,
      //         index,
      //         itemEyeStatus: true,
      //       },
      //     ],
      //   };
      // } else {
      //   lesionDataList[item.id] = {
      //     id,
      //     color,
      //     lesion: dictData.lesionList[lesion].name,
      //     code: lesion,
      //     tool,
      //     index,
      //     eyeStatus: true,
      //   };
      // }
      imageDataList[item.id] = {
        id,
        result,
        resultDetailMap,
        resultType,
        index,
      };
      if (imageDataList[item.id].resultDetailMap) {
        imageDataList[item.id].result =
          imageDataList[item.id].resultDetailMap[imageDataList[item.id].result];
      }
      imageDataList[item.id].result =
        typeof imageDataList[item.id].result === 'string'
          ? JSON.parse(imageDataList[item.id].result)
          : imageDataList[item.id].result;
      // 根据小征象组件处理聚合为字典对象
      const tempArr = dataList.lesionToImageSeriesList[item.lesion];
      const tempResult =
        tempArr &&
        tempArr.map((it) => {
          const filterObj =
            item.imageCompResultList &&
            item.imageCompResultList.find((t) => t.componentId === it.id);
          let tempObj = _.cloneDeep({
            ...it,
            ...dictData.imageSeriesCompList[it.componentId],
            data: changeSeriesOptionsData(
              dictData.imageSeriesCompList[it.componentId].data,
              dictData.imageSeriesCompList[it.componentId].parameter
                ? JSON.parse(
                    dictData.imageSeriesCompList[it.componentId].parameter
                  )
                : null,
              dictData.imageSeriesCompList[it.componentId].type
            ),
            parameter: dictData.imageSeriesCompList[it.componentId].parameter
              ? JSON.parse(
                  dictData.imageSeriesCompList[it.componentId].parameter
                )
              : null,
            id: -1, //新增的还未生成id
            result: formatFormResult(
              it.result,
              dictData.imageSeriesCompList[it.componentId].type
            ),
          });
          // filterObj 为未定义则组件为新增
          if (filterObj) {
            tempObj.id = filterObj.id;
            (tempObj.parameter = dictData.imageSeriesCompList[
              filterObj.componentId
            ].parameter
              ? JSON.parse(
                  dictData.imageSeriesCompList[filterObj.componentId].parameter
                )
              : null),
              (tempObj.result = formatFormResult(
                filterObj.result,
                dictData.imageSeriesCompList[it.componentId].type
              ));
          }
          return tempObj;
        });
      imageSeriesDataList[item.id] = tempResult;
    });
  // console.log(videoDataList, 'videoDataList');
  // 大征象数据处理
  const seriesDataList = {} as {[x: string | number]: any};
  /*if (dataList.resultDataList.seriesCompResultList?.length === 0) {
    // @ts-ignore
    dataList.resultDataList.seriesCompResultList = Object.values(dictData.seriesCompList);
  }*/
  seriesDataList[dataList.resultDataList.seriesUid] = [];
  Object.values(dictData.seriesCompList).length !== 0 && Object.values(dictData.seriesCompList).map(item => {
    const filterObj = dataList.resultDataList.seriesCompResultList && dataList.resultDataList.seriesCompResultList.find(t => t.componentId === item.id);
    let tempObj = _.cloneDeep({
      ...item,
      ...dictData.seriesCompList[item.componentId],
      data: changeSeriesOptionsData(dictData.seriesCompList[item.componentId].data, dictData.seriesCompList[item.componentId].parameter ? JSON.parse(dictData.seriesCompList[item.componentId].parameter) : null, dictData.seriesCompList[item.componentId].type),
      parameter: dictData.seriesCompList[item.componentId].parameter ? JSON.parse(dictData.seriesCompList[item.componentId].parameter) : null,
      id: -1,//新增的还未生成id
      result: formatFormResult(item.result, dictData.seriesCompList[item.componentId].type)
    })
    if (filterObj) {
      tempObj.id = filterObj.id;
      tempObj.parameter = dictData.seriesCompList[filterObj.componentId].parameter ? JSON.parse(dictData.seriesCompList[filterObj.componentId].parameter) : null,
      tempObj.result = formatFormResult(filterObj.result, dictData.seriesCompList[item.componentId].type)
    }
    seriesDataList[dataList.resultDataList.seriesUid].push(tempObj);
    // return tempObj;
  })
  // 针对超声视频算法追踪进行数据排序
  if (dataList.pageSettingList.imageLayout === 'VIDEO_ANNO') {
    for (const key in lesionDataList) {
      const element = lesionDataList[key]
      if (Array.isArray(element) && +key !== 0) {
        lesionDataList[key] = _.orderBy(element, ['alg'], ['asc'])
      }
    }
  }
  // return {
  //   lesionDataList,
  //   imageDataList,
  //   imageSeriesDataList,
  //   seriesDataList,
  //   frameList
  // }
  return _.cloneDeep({
    lesionDataList,
    imageDataList,
    imageSeriesDataList,
    seriesDataList,
    frameList
  })
}

/**
 * 将接口数据的征象结果result格式转换会form的数据格式
 * @param result 当前征象结果数据
 * @param type 当前征象结果类型
 * @returns 返回格式化后的数据结果
 */
export const formatFormResult = (result: string | undefined, type: string) => {
  // if (!result) return  null;
  // if (type === "checkbox") {
  //   return result.includes(",") ? result.split(',') : [result];
  // }
  // if (type === "child_select") {
  //   return result.includes("@#@") ? result.split('@#@') : [result];
  // }
  // return  result;
  if (result) {
    if (type === "checkbox") {
      if (result.includes(",")) {
        return result.split(',');
      } else {
        return [result];
      }
    }
    if (type === "child_select") {
      if (result.includes("@#@")) {
        return result.split('@#@');
      } else {
        return [result];
      }
    }
    if (type !== "checkbox" || "child_select") {
      return result;
    }
  } else {
    return null;
  }
}

/**
 * 对象转换成数组形式通用方法
 * @param list 当前需要转换的对象
 * @returns 转换成数组
 */
export const ObjectToArray = (list: FilmReadType.LesionItem): FilmReadType.LesionItem[] => {
  return Object.values(list);
}

/**
 * 数组转换成对象形式通用方法
 * @param list 当前需转换的数组
 * @returns 转换后对象
 */
export const ArrayToObject = (list: FilmReadType.LesionItem[]): FilmReadType.LesionItem => {
  const obj = {} as FilmReadType.LesionItem;
  list.length !== 0 && list.map(item => {
    obj[item.id] = item;
  })
  return obj;
}

/**
 * 转换征象数据方法
 * @param data 接口的JSON字符串
 * @returns 返回转换后的结果
 */
export const changeSeriesOptionsData = (data: string | null, parameter: {[x: string | number]: any} | null, type: string) => {
  let resList:any[] = []
  if (data) {
    const parseData = JSON.parse(data || "{}");
    resList = getOptionData(parseData);
    if (type === "checkbox" && parameter) {
      if (parameter.hasnull) {
        resList.push(_.cloneDeep({
          label: "无",
          value: "-1",
          children: null
        }))
      }
    }
  }
  return resList;
}

/**
 * 递归处理当前数据转换成页面展示数据结构
 * @param dataList 通过接口转换的数组
 * @returns 转换后的数组结果
 */
export const getOptionData = (dataList: any[]) => {
  if (!dataList) return [];
  dataList = dataList.map(
    (item: { child: any[]; code: string; text: string }) => {
      let obj = {
        value: '',
        label: '',
        children: null as unknown,
      };
      if (item.child && item.child.length > 0) {
        obj.value = item.code.toString();
        obj.label = item.text;
        obj.children = getOptionData(item.child);
      } else {
        obj.value = item.code.toString();
        obj.label = item.text;
      }
      return obj;
    }
  );
  return dataList;
}